from celery import Celery
from sqlalchemy import create_engine, delete
from sqlalchemy.orm import sessionmaker
from datetime import datetime

from app.core.config import settings
from app.db.models import URL

celery = Celery('tasks', broker=settings.REDIS_URL)

engine = create_engine(settings.DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

@celery.task
def cleanup_expired_urls():
    """清理过期的短链接"""
    db = SessionLocal()
    try:
        stmt = delete(URL).where(
            URL.expires_at < datetime.utcnow()
        )
        db.execute(stmt)
        db.commit()
    finally:
        db.close()

@celery.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    """设置定期清理任务"""
    sender.add_periodic_task(
        3600.0,  # 每小时执行一次
        cleanup_expired_urls.s(),
        name='cleanup-expired-urls'
    ) 